(function (factory) {
  "use strict";
  if (typeof define == 'function' && define.amd) {
    define([], factory)
  } else if (typeof exports == 'object') {
    module.exports = factory()
  } else {
    window.uPaint = factory()
  }
}(function () {
  "use strict";
  var API_SERVER_HOST = "https://courseapi.tongshike.cn"
  var RESOURCE_SERVER_HOST = "https://leicloud.ulearning.cn"
  function getCookie(c_name) {
    if (document.cookie.length > 0) {
      var c_start = document.cookie.indexOf(c_name + "=");
      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        var c_end = document.cookie.indexOf(";", c_start);
        if (c_end == -1) c_end = document.cookie.length;
        return unescape(
          document.cookie
          .substring(c_start, c_end)
          .replace(/(%[0-9A-Z]{2})+/g, unescape)
        );
      }
    }
    return "";
  }

  
  function uPaint(params) {
    this.domId = params.domId
    this.$dom = $('#' + params.domId)
    this.originalImage = params.originalImage
    this.angle = params.angle || 0
    this.markedImage = params.markedImage
    this.MAX_WIDTH = params.MAX_WIDTH || 900
    this.options = params
    this.init()
  }
 
  uPaint.prototype.init = function () {
    var self = this
    var img = new Image()
    var oriImg = self.originalImage.split('?')[0] + '?imageslim|imageMogr2/rotate/' + self.angle
    if (self.markedImage) {
      img.src = self.markedImage
    } else {
      img.src = oriImg
    }
    img.setAttribute('crossorigin', 'anonymous')
    img.onload = function (data) {
      var width = this.width
      var height = this.height
      if (width > self.MAX_WIDTH) {
        height = (height / width) * self.MAX_WIDTH
        width = self.MAX_WIDTH
      }
      self.$dom.css({
        width: width + 'px',
        height: height + 'px',
        'background-image': 'url(' + oriImg + ')',
      })
      var config = {
        menuOffsetLeft: 0,
        menuOffsetTop: 0,
        path: self.options.path || '/',
        menuHandle: false,
        imageStretch: true,
        saveImg: function (image) {
          self.saveImg(image, function () {
            console.log(self)
          })
        },
        clockwise: function () {
          self.rotate(90)
        },
        counterclockwise: function () {
          self.rotate(-90)
        },
      }
      if (self.markedImage) {
        config.image = self.getBase64Image(img)
      }
      self.$dom.wPaint(config)
    }
  }
  uPaint.prototype.rotate = function (deg) {
    var self = this
    if (self.isRotating) return
    self.isRotating = true
    var editAngle = self.angle + deg
    if (editAngle < 0) {
      editAngle += 360
    }
    if (editAngle >= 360) {
      editAngle -= 360
    }
    self.angle = editAngle
    self.originalImage = self.originalImage.split('?')[0] + '?imageslim|imageMogr2/rotate/' + self.angle
    var img = new Image()
    img.src = self.originalImage
    img.onload = function () {
      var width = this.width
      var height = this.height
      if (width > self.MAX_WIDTH) {
        height = (height / width) * self.MAX_WIDTH
        width = self.MAX_WIDTH
      }
      self.$dom.css({
        width: width + 'px',
        height: height + 'px',
        'background-image': 'url(' + self.originalImage + ')',
      })
      var imageData = self.$dom.wPaint('image')

      setTimeout(function () {
        self.rotateBase64Img(imageData, deg, function (image) {
          self.$dom.wPaint('clear')
          self.$dom.wPaint('resize')
          self.$dom.wPaint('image', image)
          self.isRotating = false
        })
      })
    }
  }

  uPaint.prototype.rotateBase64Img = function (src, edg, callback) {
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    var imgW // 图片宽度
    var imgH // 图片高度
    var size // canvas初始大小
    if (edg % 90 !== 0) {
      console.error('旋转角度必须是90的倍数!')
      return -1
    }
    edg < 0 && (edg = (edg % 360) + 360)
    const quadrant = (edg / 90) % 4 // 旋转象限
    const cutCoor = {
      sx: 0,
      sy: 0,
      ex: 0,
      ey: 0,
    } // 裁剪坐标
    var image = new Image()
    image.crossOrigin = 'anonymous'
    image.src = src
    image.onload = function () {
      imgW = image.width
      imgH = image.height
      size = imgW > imgH ? imgW : imgH
      canvas.width = size * 2
      canvas.height = size * 2

      switch (quadrant) {
        case 0:
          cutCoor.sx = size
          cutCoor.sy = size
          cutCoor.ex = size + imgW
          cutCoor.ey = size + imgH
          break
        case 1:
          cutCoor.sx = size - imgH
          cutCoor.sy = size
          cutCoor.ex = size
          cutCoor.ey = size + imgW
          break
        case 2:
          cutCoor.sx = size - imgW
          cutCoor.sy = size - imgH
          cutCoor.ex = size
          cutCoor.ey = size
          break
        case 3:
          cutCoor.sx = size
          cutCoor.sy = size - imgW
          cutCoor.ex = size + imgH
          cutCoor.ey = size + imgW
          break
      }
      ctx.translate(size, size)
      ctx.rotate((edg * Math.PI) / 180)
      ctx.drawImage(image, 0, 0)
      var imgData = ctx.getImageData(
        cutCoor.sx,
        cutCoor.sy,
        cutCoor.ex,
        cutCoor.ey
      )
      if (quadrant % 2 === 0) {
        canvas.width = imgW
        canvas.height = imgH
      } else {
        canvas.width = imgH
        canvas.height = imgW
      }
      ctx.putImageData(imgData, 0, 0)
      callback(canvas.toDataURL())
    }
  }
  uPaint.prototype.getBase64Image  = function (img) {
    var canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height

    var ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0, img.width, img.height)

    var dataURL = canvas.toDataURL('image/png')
    return dataURL

    // return dataURL.replace("data:image/png;base64,", "");
  }
  uPaint.prototype.saveImg = function (image, callback) {
    var self = this
    var pic = image.substr(image.indexOf('base64') + 7)
    $.ajax({
      url: API_SERVER_HOST + '/files/getUptoken?fileName=' + new Date().getTime() + '.jpg',
      type: "GET",
      contentType: "text/plain",
      dataType: "json",
      headers: {
        'AUTHORIZATION': getCookie('AUTHORIZATION')
      },
      async: true,
      success: function(token, status, xhr) {
        $.ajax({
          url: 'https://up.qbox.me/putb64/-1',
          type: "POST",
          dataType: "json",
          data: pic,
          headers: {
            'Content-Type': 'application/octet-stream',
            'Authorization': 'UpToken ' + token.uptoken
          },
          async: true,
          beforeSend:function(){
          },
          success: function(result, status, xhr) {
            self.markedImage = RESOURCE_SERVER_HOST + '/' + result.key
            window.open(self.markedImage)
            callback && callback()
          },
          error: function(xhr, status, error) {
            console.log(error);
          }
        });
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  uPaint.prototype.destory = function () {
    // this.$dom.removeAttr('style class').html('')
    // $(".wPaint-menu").remove()
    this.$dom.parent().html('<div id="wPaint1"></div>')
  }
  return uPaint
}))
